//
// Created by Zeppyrz on 2025/11/5.
//

#ifndef ZEDISK_FILESERVERTASK_H
#define ZEDISK_FILESERVERTASK_H

#include <fstream>
#include <mutex>

#include "CommonTask.h"

namespace ZeDisk {

class DECLSPEC FileServerTask : public CommonTask {
 public:
  FileServerTask() = default;
  ~FileServerTask() override = default;

  void HandleMessage(const Message* msg) override;
  void WriteCallback() override;
  void HandleRawMessage(void* data, int size) override;

  static void set_current_directory(std::string directory) {
    cur_dir_mtx_.lock();
    current_directory_ = std::move(directory);
    cur_dir_mtx_.unlock();
  }

  static std::string get_current_directory() {
    std::lock_guard<std::mutex> lock(cur_dir_mtx_);
    return current_directory_;
  }

 private:
  /**
   * @brief 处理获取文件列表请求
   * @param msg 读取的消息
   */
  void GetDirectory(const Message* msg);
  /**
   * @brief 处理上传请求
   * @param msg 读取的消息
   */
  void UploadFile(const Message* msg);
  /**
   * @brief 处理下载请求
   * @param msg 读取的消息
   */
  void DownloadFile(const Message *msg);

 private:
  static std::mutex cur_dir_mtx_;
  static std::string current_directory_;  // 默认当前路径
  int file_size_;                         // 文件大小
  std::ofstream outfile_;
  int upload_size_ = 0;  // 服务端已经接收的大小

  std::ifstream inputfile_;
};

}  // namespace ZeDisk

#endif  // ZEDISK_FILESERVERTASK_H
